<template>
	<el-upload 
	class="column" 
	:accept="fileAccept" 
	:action="upload_url" 
	:headers="headers"
	:file-list="fileList" 
	:before-upload="beforeUpload" 
	:on-success="uploadSuccess" 
	:before-remove="beforeRemove"
	:on-remove="removeFile" 
	:on-preview="previewFile" 
	:disabled="downloadOnly">
		<el-button v-show="!downloadOnly" slot="trigger" size="middle" type="text" style="padding: 5px 0">{{btnName}}</el-button>
	</el-upload>
</template>

<script>
	import {
		cloneDeep
	} from 'lodash'
	import axios from 'axios'
	import {
		getToken
	} from '@/utils/auth'
	import {
		WEBAPI,
		PREAPI,
		PROXY
	} from '@/settings'
	import {
		getUploadUrl
	} from '@/api/upload.js'
	export default {
		props: {
			fileAccept: {
				type: String,
				default: 'image/*,audio/*,video/*,text/plain,application/pdf,application/rtf,application/ogg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel.addin.macroEnabled.12,application/vnd.ms-excel.sheet.binary.macroEnabled.12,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.ms-works,application/vnd.ms-project,application/vnd.openxmlformats-officedocument.presentationml.slide,application/vnd.ms-asf,.zip,.7z,.rar'
			},
			ltSize: {
				type: Number,
				default: 10
			},
			downloadOnly: {
				type: Boolean,
				default: false
			},
			fileList: {
				type: Array,
				default: () => []
			},
			btnName: {
				type: String,
				default: '上传附件'
			}
		},
		data() {
			return {
				upload_url: '',
				headers: {}
			}
		},
		created() {
			this.headers = {
				Authorization: getToken()
			}
			this.upload_url = getUploadUrl()
		},
		methods: {
			beforeUpload(file) {
				const isLtSize = file.size / 1024 / 1024 < this.$props.ltSize
				if (!isLtSize) {
					this.$message.error('上传文件不能超过 ' + this.$props.ltSize + 'MB!')
				}
				return isLtSize
			},
			uploadSuccess(response, file, fileList) {
				this.$emit('update:fileList', fileList)
			},
			beforeRemove(file, fileList) {
				if (this.$props.downloadOnly) {
					this.$message.error('不允许删除文件!')
					return false
				}
			},
			removeFile(file, fileList) {
				this.$emit('update:fileList', fileList)
			},
			previewFile(file) {
				window.open(file.response.data, '_blank')
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.el-upload-list__item:first-child{
		margin-top: 5px;
	}
</style>
